package com.doit.demo02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SuppressWarnings("all")
/*
    让服务器不结束 时刻为客户端服务
 */
public class Single_Thread_Server_plus_super {
    public static void main(String[] args) throws IOException {
        System.out.println("单线程服务器启动");
        ServerSocket serverSocket = new ServerSocket(6666);
        //创建10个线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        while (true) {
            Socket accept = serverSocket.accept();//叉车
            executorService.submit(() -> {
                try {
                BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
                FileOutputStream fis = new FileOutputStream(System.currentTimeMillis() + ".jpg");
                BufferedOutputStream bos = new BufferedOutputStream(fis);
                byte[] b = new byte[1024 * 8];
                int len;
                while ((len=bis.read(b))!=-1){
                    bos.write(b,0 ,len );
                }

                System.out.println("等待中");
                OutputStream out = accept.getOutputStream();
                out.write("上传成功".getBytes());
                out.close();

                bos.close();
                bis.close();
                accept.close();
                System.out.println("文件上传已保存");
            }catch (IOException e){
                e.printStackTrace();
            }
            });
        }
    }
}
